package com.peng.springtest.aop;

import com.google.common.collect.ImmutableList;
import com.peng.utils.JacksonUtil;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;

/**
 * Aspect1
 *
 * @author lupeng10
 * @create 2024-04-15 21:16
 */
@Slf4j
@Aspect
@Component
public class Aspect1 {

    @Pointcut("@annotation(com.peng.springtest.aop.AspectAnnotation)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint jp) throws Throwable {
        MethodSignature ms = ((MethodSignature) jp.getSignature());
        // 获取注解
        AspectAnnotation annotation = ms.getMethod().getAnnotation(AspectAnnotation.class);
        Object result = jp.proceed();
        String json = JacksonUtil.toJson(result);
        Object re = JacksonUtil.fromJson(json, ms.getMethod().getReturnType());
        System.out.println(re);

        ExpressionParser parser = new SpelExpressionParser();
        LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();
        String[] parameterNames = discoverer.getParameterNames(ms.getMethod());
        Object[] args = jp.getArgs();
        EvaluationContext context = new StandardEvaluationContext();
        if (parameterNames != null) {
            for (int i = 0; i < parameterNames.length; i++) {
                context.setVariable(parameterNames[i], args[i]);
            }
        }
        // long age, Set<String> labelKeys
        List<String> ps = ImmutableList.of("#age", "#labelKeys", "#type");
        for (String p : ps) {
            Expression expression = parser.parseExpression(p);
            String value = expression.getValue(context, String.class);
            System.out.println(value);
        }

        return re;
    }
}
